package sparkStream

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe


object SparkKafka {

  def main(args: Array[String]): Unit = {

    // Spark conf
    val conf = new SparkConf().setMaster("local[*]").setAppName("Spark Kafka Consumer")//local[*]表示本地有多少资源用多少资源
    //进行流式处理，微批次处理，间隔时间2秒
    val ssc = new StreamingContext(conf,Seconds(2)) //要到依赖
    ssc.sparkContext.setLogLevel("error")
    //配置broker,key,value,groupid,
    val kakaParams = Map[String, Object](
      "bootstrap.servers" -> "192.168.136.128:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false:java.lang.Boolean),
    )

    val topicName = Array("t15")
    val streamRdd = KafkaUtils.createDirectStream[String,String](
      ssc,PreferConsistent,
      Subscribe[String,String](topicName,kakaParams)
    )

    streamRdd.foreachRDD(
      x=>{
        if(! x.isEmpty()){
          val line = x.map(_.value())
          line.foreach(println)//数据处理，期末项目周
        }
      }
    )
    //开始scc
    ssc.start()
    ssc.awaitTermination()//监控
  }

}
